<?php
/**
 * ============================================================================
 * MXCMall开源商城
 * 官网地址:http://www.mothink.cn
 * 联系QQ:510858687
 * ============================================================================
 * 会员服务类
 */

namespace Api\Model;
class UsersModel extends BaseModel {

    /**
     * 会员登录
     * @param type $userPhone
     * @param type $pwd
     * @return type
     */
    public function login($userPhone, $pwd) {
        $m = M('users');
        if ($userPhone == '' || $pwd == '')
            return array('code' => 0, 'info' => '请将信息填写完整!');
        $userinfo = $m->where(array('userPhone' => $userPhone))->find();
         
        if ($userinfo['userId'] <= 0)
            return array('code' => 0, 'info' => '用户不存在!');
 
        if ($userinfo['loginPwd'] != md5($pwd . $userinfo['loginSecret']))
            return array('code' => 0, 'info' => '密码错误!');
        if ($userinfo['userStatus'] == 0) {
            $rt = array();
            $rt['code'] = 100002;
            $rt['info'] = '你的账号已被停用，请联系客服：075582438858!';
            return $rt;
        }

        $data = array();
        $rd = array();
        $data['userId'] = $userinfo['userId'];
        $data['token'] = md5($userinfo['userId'] . time() . rand(1000, 9999));
        $data['pushToken'] = I('pushToken', '');
        $data['time'] = time();
        $rd['code'] = 1;
        $rd['info'] = '登录成功!';
        $rd['userId'] = $userinfo['userId'];
        $rd['userType'] = $userinfo['userType'];
        $rd['userStatus'] = $userinfo['userStatus'];
        $rd['userFlag'] = $userinfo['userFlag'];
        $rd['token'] = $data['token'];
        $m = M('login_token');
        $isToken = $m->where(array('userId' => $userinfo['userId']))->find();
        if ($isToken['userId'] > 0) {
            $m->save($data);
        } else {
            $m->add($data);
        }

        $data = array();
        $data['pushToken'] = I('pushToken', '');
        if ($data['pushToken']) {
            $data['userId'] = $userinfo['userId'];
            $data['time'] = time();
            $m = M('user_pushtoken');
            $isPushToken = $m->where(array('pushToken' => $data['pushToken']))->find();
            if ($isPushToken['userId'] > 0) {
                $m->where('userId = ' . $data['userId'])->save($data);
            } else {
                $m->add($data);
            }
        }


        $data = array();
        $data["userId"] = $userinfo['userId'];
        $data["lastTime"] = date('Y-m-d H:i:s');
        $data["lastIP"] = get_client_ip();
        M('users')->save($data);

        $data = array();
        $data["userId"] = $userinfo['userId'];
        $data["loginTime"] = date('Y-m-d H:i:s');
        $data["loginIp"] = get_client_ip();
        M('log_user_logins')->add($data);
        $rd['rongToken'] = $userinfo['rongToken'];
        $rd['userName'] = $userinfo['userName'];
        $rd['userPhoto'] = $userinfo['userPhoto'];
        return $rd;
    }

    /**
     * 会员注册
     */
    public function regist() {
        $m = M('users');
        $rd = array('status' => 0, 'msg' => 'Error!');

        $data = array();
        $data['userPhone'] = I('userPhone');
        $data['loginPwd'] = I("loginPwd");
        $data['reUserPwd'] = I("reUserPwd");
        $data['protocol'] = I("protocol");
        $data['loginName'] = I('userPhone');
        $data['userName'] = I('userPhone');
        if (!preg_match("#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#", $data['userPhone'])) {
            $rd["status"] = 0;
            $rd['msg'] = '手机号码格式错误!';
            return $rd;
        }
        $rs = $this->checkUserPhone($data['userPhone']);
        if ($rs["status"] != 1) {
            return $rs;
        }
        if ($data['loginPwd'] != $data['reUserPwd']) {
            $rd['status'] = 0;
            $rd['msg'] = '两次输入密码不一致!';
            return $rd;
        }
        $mobileCode = I("mobileCode");
        $verify = session('VerifyCode_userPhone');
        $startTime = (int) session('VerifyCode_userPhone_Time');
        if ((time() - $startTime) > 300) {
            $rd['status'] = 0;
            $rd['msg'] = '验证码已超过有效期!';
            return $rd;
        }
        if ($mobileCode == "" || $verify != $mobileCode) {
            $rd['status'] = 0;
            $rd['msg'] = '验证码错误!';
            return $rd;
        }
        if ($data['protocol'] != 1) {
            $rd['status'] = 0;
            $rd['msg'] = '必须同意使用协议才允许注册!';
            return $rd;
        }
        foreach ($data as $v) {
            if ($v === '') {
                $rd['status'] = 0;
                $rd['msg'] = '注册信息不完整!';
                return $rd;
            }
        }
        unset($data['reUserPwd']);
        unset($data['protocol']);
        //检测账号，邮箱，手机是否存在
        $data["loginSecret"] = rand(1000, 9999);
        $data['loginPwd'] = md5(I('loginPwd') . $data['loginSecret']);
        $data['userType'] = 0;
        $data['createTime'] = date('Y-m-d H:i:s');
        $data['userFlag'] = 1;


        $rs = $m->add($data);
        $this->setRongCloudUserToke($rs, $data['userPhone']);
        if (false !== $rs) {
            $rd['status'] = 1;
            $rd['userId'] = $rs;
            $rd['msg'] = '注册成功!';
        }
        if ($rd['status'] > 0) {
            $token = $this->login($data['userPhone'], I("loginPwd"));
            if ($token['code'] == 0)
                return $token;
        }


        return array_merge($rd, $token);
    }

    /**
     * 找回密码
     */
    public function rePwd() {
        $m = M('users');
        $data = array();
        $data['userPhone'] = I('userPhone');
        $data['loginPwd'] = I("loginPwd");
        $data['reUserPwd'] = I("reUserPwd");
        $rd = array('status' => -1);

        if ($data['loginPwd'] == '' || $data['reUserPwd'] == '') {
            $rd['status'] = -7;
            $rd['msg'] = '输入信息不完整!';
            return $rd;
        }
        if (!preg_match("#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#", $data['userPhone'])) {
            $rd["status"] = -4;
            $rd['msg'] = '手机号码格式错误!';
            return $rd;
        }
        if ($data['loginPwd'] != $data['reUserPwd']) {
            $rd['status'] = -3;
            $rd['msg'] = '两次输入密码不一致!';
            return $rd;
        }
        $rs = $this->checkUserPhone($data['userPhone']);
        if ($rs["status"] == 1) {
            $rd['status'] = -9; 
            $rd['msg'] = '该手机账号不存在!';
            return $rd;
        }
        $mobileCode = I("mobileCode");
        $verify = session('VerifyCode_userPhone');
        $startTime = (int) session('VerifyCode_userPhone_Time');
        if ((time() - $startTime) > 300) {
            $rd['status'] = -5;
            $rd['msg'] = '验证码已超过有效期!';
            return $rd;
        }
        if ($mobileCode == "" || $verify != $mobileCode) {
            $rd['status'] = -8;
            $rd['msg'] = '验证码错误!';
            return $rd;
        }

        unset($data['reUserPwd']);
        $data["loginSecret"] = rand(1000, 9999);
        $data['loginPwd'] = md5(I('loginPwd') . $data['loginSecret']);
        $rs = $m->where(array('userPhone' => $data['userPhone']))->save($data);
        if (false !== $rs) {
            $rd['status'] = 1;
            $rd['userId'] = $rs;
            $rd['msg'] = '密码修改成功!';
        }

        return $rd;
    }

    /**
     * 查询用户手机是否存在
     */
    public function checkUserPhone($userPhone) {
        $userId = I("userId");

        $rd = array('status' => -2, 'msg' => '该手机号码已注册!');

        $m = M('users');
        $sql = " userFlag=1 and userPhone='" . $userPhone . "'";
        if ($userId > 0) {
            $sql .= " AND userId <> $userId";
        }
        $rs = $m->where($sql)->count();

        if ($rs == 0)
            $rd['status'] = 1;
        return $rd;
    }

    /**
     * 检查开店类型状态
     * @param type $userInfo
     * @return int
     */
    public function checkShopStauts($userInfo) {
//        $sql = "select u.userId, u.userType from __PREFIX__users u where 1 ";
//        $row = $this->queryRow($sql);
        if ($userInfo['userType'] == 0) {
            return array();
        }
        $shop = M('shops')->where('userId = ' . $userInfo['userId'])->field('shopId, shopStatus,depositId,depositMoney')->find();
        $shop['remark'] = M('shops_auth')->where('shopId=' . $shop['shopId'])->getField('remark');
        return $shop;
    }

    /**
     * 个人资料
     * @param type $userId
     * @return type
     */
    public function getProfile($userId) {
        $m = M('users');
        $data = $m->where('userId=' . $userId)->field('userId,loginName,userName,rongToken,userSex,userPhone,userPhoto,userType')->find();
        if ($data['userType'] > 0) {
            $data['shop'] = M('shops')->where('userId=' . $data['userId'])->field('shopId,(shopId+100000) shopSn,userId,shopName,shopImg,shopTel,shopAddress,province,city,district,depositId,depositMoney')->find();
            if ($data['shop']['depositId'] > 0) {
                $data['shop']['deposit'] = M('shops_deposit')->where('id=' . $data['shop']['depositId'])->field('level,icon,title')->find();
            } else {
                $data['shop']['deposit'] = array();
            }
            $data['shop']['isFriend'] = $this->isFriend($userId, $data['shop']['userId']);
            $data['shop']['isFollow'] = $this->isFollow($userId, $data['shop']['shopId']);
        } else {
            $data['shop'] = array();
        }

        return $data;
    }

    /**
     * 编辑个人资料
     * @param type $userId
     * @return type
     */
    public function editProfile($userId) {
        $m = M('users');
        $m->userName = I('userName');
        $m->userSex = I('userSex');
        $m->userPhone = I('userPhone');
        $m->loginName = I('userPhone');
        $m->userPhoto = I('userPhoto');

        $rs = $m->where('userId=' . $userId)->save();

        return $rs;
    }

    /**
     * 添加|编辑用户地址
     * @param type $userId
     * @return type
     */
    public function editAddress($userId) {
        $m = M('user_address');
        $m->userId = $userId;
        $m->userName = I('userName');
        $m->userPhone = I('userPhone');
        $m->areaId1 = I('provinceId');
        $m->areaId2 = I('cityId');
        $m->areaId3 = I('districtId');
        $m->province = I('province');
        $m->city = I('city');
        $m->district = I('district');
        $m->address = I('address');
        $m->postCode = I('postCode');

        if (I('addressId', 0) > 0) {
            $rs = $m->where('addressId=' . I('addressId'))->save();
        } else {
            $m->createTime = date('Y-m-d H:i:s');
            $rs = $m->add();
        }

        return $rs;
    }

    /**
     * 地址详细信息
     * @param type $userId
     * @return type
     */
    public function getAddress($userId) {
        $m = M('user_address');
        $data = $m->where('addressId=' . I('addressId'))->field('addressId,userName,userPhone,areaId1,areaId2,areaId3,address,province,city,district,postCode')->find();

        return $data;
    }

    /**
     * 设置默认地址
     * @param type $userId
     * @return type
     */
    public function setDefaultAddress($userId) {
        $m = M('user_address');
        $addressId = I('addressId');
        $rs = $m->where('userId=' . $userId)->save(array('isDefault' => 0));
        $rs = $m->where('addressId=' . $addressId)->save(array('isDefault' => 1));

        return $rs;
    }

    /**
     * 用户地址列表
     * @param type $userId
     * @return type
     */
    public function getAddressList($userId) {
        $m = M('user_address');
        $data = $m->where('userId=' . $userId)->field('addressId,userName,userPhone,areaId1,areaId2,areaId3,address,province,city,district,postCode,isDefault')->order('isDefault DESC, addressId DESC')->select();

        return $data;
    }

    /**
     * 删除用户地址
     * @param type $userId
     * @return type
     */
    public function delAddress($userId) {
        $m = M('user_address');
        $addressId = I('addressId');
        $rs = $m->where('addressId=' . $addressId)->delete();

        return $rs;
    }

    /**
     * 关注商品
     * @param type $userId
     * @return type
     */
    public function followGoods($userId) {
        $m = M('favorites');
        $goodsId = I('goodsId');
        $count = $m->where('userId=' . $userId . ' AND goodsId=' . $goodsId)->count();
        if ($count > 0)
            return -1;
        $m->userId = $userId;
        $m->goodsId = $goodsId;
        $m->createTime = date('Y-m-d H:i:s');
        $rs = $m->add();

        return $rs;
    }

    /**
     * 关注店铺
     * @param type $userId
     * @return type
     */
    public function followShop($userId) {
        $m = M('favorites');
        $shopId = I('shopId');
        $count = $m->where('userId=' . $userId . ' AND shopId=' . $shopId)->count();
        if ($count > 0)
            return -1;
        $m->userId = $userId;
        $m->shopId = $shopId;
        $m->createTime = date('Y-m-d H:i:s');
        $rs = $m->add();

        return $rs;
    }

    /**
     * 关注列表
     * @param type $userId
     * @return type
     */
    public function getFollowList($userId) {
        $type = I('type', 'goods');
        if ($type == 'goods') {
            $sql = "select f.id,g.goodsId,g.goodsName,g.shopPrice,g.goodsThumbs from __PREFIX__favorites f, __PREFIX__goods g where f.goodsId = g.goodsId and f.userId = " . $userId . ' order by f.id DESC';
            $data = $this->query($sql);
        } elseif ($type == 'shop') {
            $sql = "select f.id,s.shopId,s.shopName,s.shopImg,s.shopStatus from __PREFIX__favorites f, __PREFIX__shops s where f.shopId = s.shopId and f.userId = " . $userId . ' order by f.id DESC';
            $data = $this->query($sql);
        }

        return $data;
    }

    /**
     * 删除关注
     * @param type $userId
     * @return type
     */
    public function delFollow() {
        $m = M('favorites');
        $rs = $m->where('id=' . I('id'))->delete();

        return $rs;
    }

    /**
     * 用户钱包
     * @param type $userId
     * @return type
     */
    public function userBurse($userId) {
        $m = M('users');
        $rs = $m->where('userId=' . $userId)->field('userId,userBalance,userFreeze')->find();
        $shopInfo = M('shops')->where('userId = ' . $userId)->find();

        $profit_sum = 0;
        if ($shopInfo['shopId'] > 0) {
            $orderIds = M('orders')->where('shopId = ' . $shopInfo['shopId'] . ' and orderFlag = 1 and orderStatus in (-3,0,1,2,3)')->select();
            $ids = '';
            if (!empty($orderIds)) {
                foreach ($orderIds as $v) {
//                    $ids .= $v['orderId'] . ',';
                    $ids .= $v['orderNo'] . ',';
                }
            }
            $ids = '(' . trim($ids, ',') . ')';
            $profit_sum = M('log_user_profit')->where('profitStatus = 0 and shopId = ' . $shopInfo['shopId'] . ' and orderNo in ' . $ids)->getField("sum(`profit`)");
//            $profit_sum = M('log_user_profit')->where('shopId = ' . $shopInfo['shopId'] . ' and orderStatus in (0,1,2,3)')->getField("sum(`profit`)");ÏÏÏÏ
        }
        $rs['userFreeze'] = sprintf('%.2f', $rs['userFreeze'] + $profit_sum + $shopInfo['depositMoney']);

        return $rs;
    }

    /**
     * 添加银行卡
     * @param type $userId
     * @return type
     */
    public function userBankcard($userId) {
        $m = M('user_bankcard');

        $data = array();
        $data['userId'] = $userId;
        $data['bankId'] = I('bankId');
        $data['bankName'] = M('banks')->where('bankId=' . $data['bankId'])->getField('bankName');
        $data['cardNum'] = I('cardNum');
        $data['userName'] = I('userName');
        $data['userPhone'] = I('userPhone');

        $rs = $m->add($data);

        return $rs;
    }

    /**
     * 银行卡列表
     * @param type $userId
     * @return type
     */
    public function bankcardList($userId) {
        $m = M('user_bankcard');

        $data = $m->where('userId=' . $userId)->order('cardId DESC')->select();

        return $data;
    }

    /**
     * 删除银行卡
     * @param type $userId
     * @return type
     */
    public function delBankcard($userId) {
        $m = M('user_bankcard');

        $cardId = I('cardId');
        $rs = $m->where('userId=' . $userId . ' AND cardId=' . $cardId)->delete();

        return $rs;
    }

    /**
     * 资金记录
     * @param type $userId
     * @return type
     */
    public function logBalanceList($userId) {
        $m = M('log_user_balance');
        $num = I('num') ? I('num') : 10;
        $page = I('page') ? I('page') : 1;
        $page = ($page - 1) * $num;
        $logType = I('logType', 0);
        $startTime = I('startTime') ? I('startTime') : date("Y-m-d", strtotime("-15 day"));
        $endTime = I('endTime') ? date('Y-m-d', strtotime(I('endTime')) + (3600 * 24)) : date("Y-m-d", strtotime("2 day"));

        $where = 'userId = ' . $userId;
        if ($logType > 0)
            $where .= ' and logType = ' . $logType;
        $where .= " and logTime >= '" . $startTime . "'";
        $where .= " and logTime <= '" . $endTime . "'";

        $data = $m->where($where)->order('logId desc')->field("logId,userId,logContent,typeName,price,current_balance,date_format(`logTime`, '%Y-%m-%d') AS logTime")->limit($page, $num)->select();

        return $data;
    }

    /**
     * 可提现详情
     */
    public function canTakeCash($userId) {
        $m = M('users');

        $data = $m->where('userFlag =1 and userId=' . $userId)->field('userId,userBalance')->find();
        if (empty($data))
            return;
        $data['bankcard'] = M('user_bankcard')->where('userId=' . $userId)->select();

        return $data;
    }

    /**
     * 提现
     * @param type $userId
     * @return string
     */
    public function takeCash($userId) {
        $rt = array('code' => 0, 'info' => 'Error!');
        $price = I('price');
        $cardId = I('cardId');

        if (empty($price) || empty($cardId)) {
            return $rt;
        }

        $m = M('users');
        $balance = $m->where('userFlag =1 and userId=' . $userId)->getField('userBalance');

        if ($price > $balance) {
            $rt['info'] = '提现金额不得大于账户余额!';
            return $rt;
        }
        $card = M('user_bankcard')->where('cardId=' . $cardId)->field('bankName,cardNum,userName,userPhone')->find();
        $card['price'] = $price;
        $card['cashTime'] = date('Y-m-d H:i:s');
        $card['userId'] = $userId;

        $rs = $m->where('userId=' . $userId)->setDec('userBalance', $price);
        $this->MlogBalance($userId, $price, 3, '用户提现');
        $rs = M('user_cash')->add($card);

        if ($rs == FALSE)
            return $rt;
        $rt['code'] = 1;
        $rt['info'] = 'Success!';

        return $rt;
    }

    /**
     * 充值记录
     * @param type $userId
     * @return type
     */
    public function depositLog($userId) {
        $m = M('user_deposit_log');

        $data = array();
        $data['userId'] = $userId;
        $data['orderSN'] = substr(time(), 2);
        $data['priceSum'] = I('price');
        $data['type'] = 1;
        $data['payType'] = I('payType');
        $data['time'] = date('Y-m-d H:i:s');

        $rs = $m->add($data);
        if ($rs == FALSE)
            return $rs;
        return $data;
    }

    /**
     * 系统消息
     */
    public function sysMsgList($userId) {
        $m = M('user_sys_msg');
        $data = $m->where('userId=' . $userId)->order('id desc')->limit(200)->select();

        return $data;
    }

    /**
     * 系统消息详情
     */
    public function sysMsgInfo($userId) {
        $m = M('user_sys_msg');
        $id = I('id', 0);
        if ($id == 0)
            return;
        $rs = $m->where('userId=' . $userId . ' and id = ' . $id)->save(array('isRead' => 1));
        $data = $m->where('userId=' . $userId . ' and id = ' . $id)->find();
        error_log("sysMsgInfo line 652 sql=".$m->getLastSql()."\r\n",3,LOG_PATH."/__sysMsgInfo.log");
        error_log("sysMsgInfo line 652 data=".json_encode($data)."\r\n",3,LOG_PATH."/__sysMsgInfo.log");
        return $data;
    }

    /**
     * 修改密码error_log
     */
    public function modifyPassword($userId) {
        $m = M('users');
        $rt = array();
        $rt['code'] = 0;
        $rt['info'] = 'Error!';

        $oldPwd = I('oldPwd', '');
        $newPwd = I('newPwd', '');
        $reNewPwd = I('reNewPwd', '');

        $user = $m->where('userId=' . $userId)->find();
        if ($oldPwd == '' || $newPwd == '' || $reNewPwd == '') {
            $rt['info'] = '请输入完整信息!';
            return $rt;
        }
        if ($newPwd != $reNewPwd) {
            $rt['info'] = '两次新密码不一致!';
            return $rt;
        }
        if ($user['loginPwd'] != md5($oldPwd . $user['loginSecret'])) {
            $rt['info'] = '原密码错误';
            return $rt;
        }
        $m->loginPwd = md5($newPwd . $user['loginSecret']);
        $rs = $m->where('userId=' . $userId)->save();
        if ($rs == FALSE) {
            $rt['info'] = '密码修改失败!';
            return $rt;
        }

        $rt['code'] = 1;
        $rt['info'] = '密码修改成功!';

        return $rt;
    }

    /**
     * 获取融云TOKEN
     * @return type
     */
    public function setRongCloudUserToke($uid, $name) {
        $appKey = 'e5t4ouvptfp1a';
        $appSecret = 'LXLYdXbNnE3';

        vendor("RongCloud.ServerAPI");
        $rongCloud = new \RongServerAPI($appKey, $appSecret);

//        $uid = 1;
//        $name = '13751082273';
        $portraitUri = C('WEB_URL') . '/Public/images/default_haeder.png';
        $token = $rongCloud->getToken($uid, $name, $portraitUri);
        $token = json_decode($token, TRUE);
        $rs = M('users')->where('userId=' . $uid)->save(array('rongToken' => $token['token']));
        return $rs;
    }

}